﻿/*
 * @Author Super听歌 qq:841739194
 * @Date 2021/2/18
 * @Version 1.0.0
 * @Description
 * 设置独立环境，设置方法，绑定lua脚本
 * 匈牙利命名规则
 * 变量名=属性+类型+对象描述
 * 全局g_  常量c_ 成员变量m_ 静态s_
 */

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using XLua;

public class LuaBehaviour : MonoBehaviour
{
    private LuaEnv m_LuaVm = Manager.LuaManager.luaEnv; //开启一个虚拟机
    protected LuaTable m_ScriptEnv;

    private Action m_LuaInit;
    private Action m_LuaUpdate;
    private Action m_LuaOnDestroy;

    internal static float lastGCTime = 0;
    internal const float GCInterval = 1;//1 second

    private void Awake()
    {
        m_ScriptEnv = m_LuaVm.NewTable(); //为每一个lua脚本配置独立环境,防止脚本全局变量，函数冲突
        LuaTable meta = m_LuaVm.NewTable();
        meta.Set("__index", m_LuaVm.Global); //设置元方法
        m_ScriptEnv.SetMetaTable(meta); //设置元表
        meta.Dispose();
        m_ScriptEnv.Set("self", this); //lua定义的self  映射 this 
    }

    public virtual void Init(string luaName)
    {
        m_LuaVm.DoString(Manager.LuaManager.GetLuaByte(luaName), luaName, m_ScriptEnv);  //绑定lua脚本的方式,建议只绑定一个Main.lua，其它lua文件加载在这个main脚本里加载
        m_ScriptEnv.Get("OnInit", out m_LuaInit);
        m_ScriptEnv.Get("OnUpdate", out m_LuaUpdate);
        m_LuaInit?.Invoke();
    }


    private void Update()
    {
        if (m_LuaUpdate != null)
        {
            m_LuaUpdate();
        }
        if (Time.time - LuaBehaviour.lastGCTime > GCInterval)
        {
            m_LuaVm.Tick();
            LuaBehaviour.lastGCTime = Time.time;
        }
    }

    private void OnDestroy()
    {
        m_LuaOnDestroy?.Invoke();
        LuaClear();
    }

    private void OnApplicationQuit()
    {
        LuaClear();
    }

    protected virtual void LuaClear()
    {
        m_LuaOnDestroy = null;
        m_ScriptEnv?.Dispose();
        m_ScriptEnv = null;
        m_LuaUpdate = null;
        m_LuaInit = null;
    }
}
